<template>
  <div class="user-mapcontent">
    <el-card class="container-card">
      <div
        slot="header"
        style="height: 60px;"
      >
        <span>作业范围</span>
        <div style="float: right; margin-right: 40px">
          <el-tooltip
            effect="dark"
            content="点击编辑释放绘制电子围栏功能"
            placement="top"
          >
            <el-button
              v-show="showEdit"
              class="save-area-btn"
              @click="editData"
            >编辑</el-button>
          </el-tooltip>
          <el-tooltip
            class="item"
            effect="dark"
            content="点击保存上传绘制好的电子围栏"
            placement="top"
          >
            <el-button
              v-show="showSave"
              class="save-area-btn"
              @click="createData"
            >提交</el-button>
          </el-tooltip>
          <el-button
            v-show="showSave"
            class="cancel-area-btn"
            @click="cancelData"
          >取消</el-button>
        </div>
      </div>
      <div class="searchBox">
        <div class="keyword">
          <label>地区关键词：</label>
          <el-input
            v-model="keyword"
            placeholder="请输入地区关键词"
          />
        </div>
      </div>
      <baidu-map
        class="map"
        :center="center"
        :zoom="zoom"
        :scroll-wheel-zoom="true"
        :map-click="false"
        @mousemove="syncPolyline"
        @click="paintPolyline"
        @rightclick="newPolyline"
        @ready="ready"
      >
        <bm-polygon
          v-for="(path, index) in polyline.paths"
          :key="index"
          :path="path"
          fill-color="rgb(177, 224, 248)"
          :fill-opacity="0.5"
          :stroke-opacity="0.1"
          :editing="polyline.editing"
          @lineupdate="updatePolygonPath"
        />
        <bm-local-search
          :keyword="keyword"
          :auto-viewport="true"
          :panel="false"
        />
        <bm-control
          v-show="showSave"
          style="background: #fff; width: 100%"
        >
          <el-button
            type="primary"
            class="new-btn"
            @click="toggle('polyline')"
          >{{ polyline.editing ? '完成绘制' : '开始绘制' }}</el-button>
          <el-button
            v-show="polyline.editing !== false"
            style="
                  color: #818693;
                  border: 1px solid #d8dde3;
                  padding: 10px 20px;
                  margin-left: 12px;
                "
            class="delet"
            @click="clearMap()"
          >删除围栏</el-button>
          <P
            style="
                  font-size: 12px;
                  color: rgb(32, 177, 245);
                  width: 100%;
                  background: rgb(177, 224, 248);
                  width: 100%;
                  height: 30px;
                  line-height: 30px;
                  text-align: left;
                  padding-left: 10px;
                "
          >！点击或拖动鼠标绘制作业范围，右击鼠标结束图形绘制，图形不可有交叉点。完成绘制后，点击提交按钮保存。每个机构仅可支持绘制一个作业范围</P>
        </bm-control>
        <bm-control
          v-show="!isHaveAgencyArange &&!showSave"
          style="background: #fff; width: 100%"
        >
          <p
            style="
                font-size: 12px;
                  color: rgb(32, 177, 245);
                  width: 100%;
                  background: rgb(177, 224, 248);
                width: 100%;
                height: 20px;
                line-height: 20px;
                text-align: center;
              "
          >
            ！ 当前{{ $route.query.agencyName }}下暂无作业范围
          </p>
        </bm-control>
      </baidu-map>

    </el-card>
  </div>
</template>

<script>
import { scopeBusiness, addMap, delMap } from '@/api/employee'
export default {
  data() {
    return {
      isHaveAgencyArange: '',
      keyword: '',
      loading: false,
      departTree: [],
      defaultList: [],
      showEdit: true,
      showSave: false,
      isHaveMap: false, // 快递员是否有作业范围
      isFirstEdit: true, // 默认存在作业范围
      isOperation: false, // 已有作业范围不可以开启划线功能
      // 地图数据
      center: {
        lng: 116.404,
        lat: 39.915
      },
      zoom: 11,
      polygonPath: [
      ],
      mapDate: {},
      polyline: {
        editing: false,
        paths: []
      } // 作业范围,绘制的多边形
    }
  },
  methods: {
    // 地图初始化
    async ready({ BMap, map }) {
      this.map = map
      this.BMap = BMap
      this.scopeBusiness()
    },
    async scopeBusiness() {
      const res = await scopeBusiness(this.$route.query.id)
      this.mapDate = res
      let pointArr = []
      let noAgencyArange = []
      if (res.polygon && res.polygon.length > 0) {
        if (Array.isArray(res.polygon)) {
          pointArr = res.polygon.map((item) => {
            return { lat: item.latitude, lng: item.longitude }
          })
        }
        this.isHaveAgencyArange = true
      } else {
        this.isHaveAgencyArange = false
        if (res.latitude) {
          noAgencyArange = [{ lat: res.latitude, lng: res.longitude }]
        } else {
          noAgencyArange = [{ lat: '39.915', lng: '116.4045' }]
        }
      }
      const viewPointInfo = this.map && this.map.getViewport(this.isHaveAgencyArange ? pointArr : noAgencyArange)
      this.$set(this.center, 'lng', viewPointInfo.center.lng)
      this.$set(this.center, 'lat', viewPointInfo.center.lat)
      this.zoom = this.isHaveAgencyArange ? viewPointInfo.zoom : 11

      this.isFirstEdit = Boolean(res.polygon && res.polygon.length > 0)
      this.agencyId = this.$route.query.id
      this.$set(this.polyline, 'paths', !pointArr ? [] : [pointArr])
      this.$set(this.polyline, 'editing', false)
    },
    selectFirstNode(arr) {
      let node = null
      if (arr[0].children && arr[0].children.length) {
        node = this.selectFirstNode(arr[0].children)
      } else {
        node = arr[0]
      }
      return node
    },
    getFirstNodeId(node) {
      const ids = [node.id]
      if (node.children && node.children.length > 0) {
        const firstChild = node.children[0]
        const childIds = this.getFirstNodeId(firstChild)
        ids.push(...childIds)
      }
      return ids
    },
    editData() {
      this.showEdit = false
      this.showSave = true
    },
    async createData() {
      this.isOperation = false
      this.polyline.editing = false
      if (this.polyline.paths.length === 0) {
        return this.$message.error('请绘制作业机构范围')
      }
      // 用于解决绘画电子围栏时，取消默认选中点的绘画开启新的绘画时，无法提交的问题
      const arr = []
      this.polyline.paths.forEach((item) => {
        arr.push(item.length)
      })
      const max = Math.max(...arr)
      const indexOfMax = arr.indexOf(max)
      // point坐标点
      const point = (
        !this.isFirstEdit ? this.polyline.paths[indexOfMax] : this.polygonPath
      ).map((item) => {
        return { latitude: item.lat, longitude: item.lng }
      })
      point.push(point[0]) // 手动在数组末尾加上第一个坐标点
      const data = {
        polygon: point,
        type: 2,
        bid: this.$route.query.id
      }
      // 发送请求，调用接口，保存数据
      await addMap(data)
        .then((res) => {
          if (res === null) {
            this.showSave = false
            this.showEdit = true
            this.$emit('newDataes', this.newDataes)
            this.$message.success('电子围栏保存成功')
            this.$set(this.polyline, 'editing', false)
          } else {
            this.$message.error(res.msg || '电子围栏保存失败')
          }
        })
        .catch(() => {
          this.$message.error('电子围栏保存失败')
        })
    },
    cancelData() {
      this.showEdit = true
      this.showSave = false
      this.polyline.editing = false
    },
    updatePolygonPath(e) {
      this.polygonPath = e.target.getPath()
    },
    async clearMap() {
      this.isOperation = false
      this.polyline.editing = false
      this.showSave = true
      this.showEdit = false
      if (!this.isFirstEdit) {
        this.$set(this.polyline, 'paths', [])
      } else {
        // 清除绘制电子围栏
        const res = await delMap(this.$route.query.id)
        if (res === null) {
          this.$message.success('删除机构作业范围成功')
          this.polyline.paths = []
        } else {
          this.$message.error(res.msg || '删除机构作业范围成功')
        }
      }
    },
    // 开启多边形绘制
    toggle(name) {
      this[name].editing = !this[name].editing
      // console.log(this.polyline.editing)
    },
    // 鼠标移动时
    syncPolyline(e) {
      if (!this.polyline.editing || !this.isOperation) {
        return
      }
      const paths = this.polyline.paths
      if (!paths.length) {
        return
      }
      const path = paths[paths.length - 1]
      if (!path.length) {
        return
      }
      if (path.length === 1) {
        path.push(e.point)
      }
      this.$set(path, path.length - 1, e.point)
    },
    // 鼠标右键多边形绘制完成
    newPolyline(e) {
      if (!this.polyline.editing) {
        return
      }
      const paths = this.polyline.paths
      if (!paths.length) {
        paths.push([])
      }
      const path = paths[paths.length - 1]
      path.pop()
      if (path.length) {
        paths.push([])
      }
    },
    paintPolyline(e) {
      if (!this.polyline.editing || this.isFirstEdit) {
        return
      }
      this.isOperation = true
      const { paths } = this.polyline
      !paths.length && paths.push([])
      paths[paths.length - 1].push(e.point)
    }
  }
}
</script>

<style lang="scss" scoped>
.user-mapcontent{
  .map-top{
    padding: 20px 25px;
    display: flex;
    justify-content:space-between;
    align-items: center;
    background-color: #f8faff;
    font-weight: 700;
  }
}
.save-area-btn {
  background-color: #e15536;
  color: #ffffff;
  width: 90px;
  border-radius: 5px;
  font-weight: 400;
  border: 1px solid #e15536;
  &:hover {
    background: #ffab98;
    border: 1px solid #ffab98;
  }
}
.cancel-area-btn {
  width: 90px;
  color: #2a2929;
  border: 1px solid #d8dde3;
  border-radius: 5px;
  font-weight: 400;
  &:hover {
    background: #ffeeeb;
    border: 1px solid #f3917c;
    color: #e15536;
  }
}
::v-deep .el-card__header {
    padding: 0 0 0 25px!important;
    border-bottom: 0!important;
    background: #f8faff!important;
    font-size: 16px!important;
    font-weight: 700!important;
    color: #2a2929!important;
    height: 60px;
    line-height: 60px;
}
.map{
  width:100%;
  height:650px;
  padding: 10px 0 0 0;
}
.delet {
  &.el-button:focus {
    background-color: #fff;
  }
}
.keyword{
  width: 200px;
  .el-input{
    margin-top: 20px;
  }
}
</style>
